import os


def convert_to_bytes(size, unit):
    """
    将给定的文件大小转换为字节。
    Args:
        size (float): 文件大小数值
        unit (str): 文件大小单位（"B", "KB", "MB", "GB"）
    Returns:
        int: 文件字节数
    """
    units = ["B", "KB", "MB", "GB"]
    unit = unit.upper()
    if unit not in units:
        raise ValueError("无效的单位")

    power = units.index(unit)
    bytes_size = size * (1024 ** power)
    return int(bytes_size)


def generate_file(file_name, file_size):
    folder_path = '../filesOutput/'
    os.makedirs(folder_path, exist_ok=True)
    file_path = os.path.join(folder_path, file_name)

    with open(file_path, 'wb') as f:
        f.seek(file_size - 1)
        f.write(b'\0')


def main():
    file_name = 'obsTest'
    size = float(input("请输入文件大小："))
    unit = input("请输入文件大小单位（B/KB/MB/GB）：")

    try:
        file_size = convert_to_bytes(size, unit)
        generate_file(file_name, file_size)

        converted_size, converted_unit = file_size, "B"
        if file_size >= 1024:
            units = ["KB", "MB", "GB"]
            for unit in units:
                converted_size /= 1024
                if converted_size < 1024:
                    converted_unit = unit
                    break

        print(f"已生成大小为 {size} {unit} 的文件（转换为字节后大小为 {file_size} B）：{file_name}，保存在 {os.path.abspath(file_name)}")
    except ValueError as e:
        print(e)


if __name__ == '__main__':
    main()